import { shallowRef } from 'vue';
import { useRouter } from 'vue-router';
import { ElButton, ElMessage } from 'element-plus';
import type { IExFormSchema } from 'element-plus-extension';
import { ExForm, ExIcon, useForm } from 'element-plus-extension';
import { useUserStore } from '@/plugins/pinia/modules/user';

export function useLoginForm() {
  const loading = shallowRef(false);
  const { replace } = useRouter();
  const userStore = useUserStore();

  const handleLogin = () => {
    validate().then(() => {
      loading.value = true;
      userStore.login(getModelValue()).then(() => {
        setTimeout(() => {
          loading.value = false;
          ElMessage.success('登录成功!');
          setTimeout(() => {
            replace('/');
          }, 500);
        }, 1000);
      });
    });
  };

  const formSchemas: Array<IExFormSchema> = [
    {
      label: '用户名',
      showLabel: false,
      prop: 'account',
      required: true,
      component: 'ExInput',
      componentProps: {
        clearable: true,
        slots: {
          prefix: () => <ExIcon icon="User" />
        }
      }
    },
    {
      label: '密码',
      showLabel: false,
      prop: 'password',
      required: true,
      component: 'ExInput',
      componentProps: {
        clearable: true,
        type: 'password',
        slots: {
          prefix: () => <ExIcon icon="Unlock" />
        }
      }
    },
    {
      label: '验证码',
      showLabel: false,
      prop: 'code',
      required: true,
      component: 'ExInput',
      componentProps: {
        clearable: true,
        slots: {
          prefix: () => <ExIcon icon="Position" />,
          append: () => <img class="ex-login-verify-image" />
        }
      }
    },
    {
      showLabel: false,
      renderContent() {
        return (
          <ElButton type="primary" round={true} loading={loading.value} class="ex-login-button" onClick={handleLogin}>
            登录
          </ElButton>
        );
      }
    }
  ];

  const [registerForm, { validate, getModelValue }] = useForm({
    schemas: formSchemas,
    baseColProps: 24,
    labelPosition: 'top',
    size: 'large',
    hideRequiredAsterisk: true
  });

  const renderForm = () => {
    return (
      <>
        <ExForm onRegister={registerForm} />
      </>
    );
  };

  return {
    renderForm
  };
}
